/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head==NULL)
        return NULL;

        ListNode *p=head,*q=p;
        while(p && p->next){
            p=p->next->next;
            q=q->next;
            if(p==q&&p!=NULL){
                q=head;
                while(q!=p){
                    q=q->next;
                    p=p->next;
                }
                return p;

            }

        }
        return NULL;

    }
};